﻿using And.Shp.Common.Misc;
using And.Shp.Common.Serialization;
using And.Shp.Common.ServiceLocation;
using Microsoft.SharePoint.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Uportal.Shp.Core.Services
{
    /// <summary>
    /// Project settings (different for various Webs)
    /// </summary>
    public class Settings
    {
        internal const string ConfigFileUrl = "Uportal.Shp.xml";

        //[XmlIgnore]
        public string ModeratorGroup { get; set; }
        public string WebUrl { get; set; }
        public bool Log { get; set; }

        public static Settings Get()
        {
            var resolver = SL.GetCurrent().GetInstance<IUrlResolver>();
            var webUrl = resolver.GetUrl("UportalUrl");

            var settsContent = SPHelper.GetElement(SPUrlUtility.CombineUrl(webUrl, ConfigFileUrl));

            Settings setts = null;

            if (!string.IsNullOrEmpty(settsContent))
                setts = SerializationFactory.Xml<Settings>().Deserialize(settsContent);

            if (setts == null)
            {
                setts = GetDefault();
                Save(webUrl, setts);
            }

            return setts;
        }

        public static void Save(string webUrl, Settings setts)
        {
            var newContent = SerializationFactory.Xml<Settings>().Serialize(setts);
            if (newContent == null) throw new Exception("Cannot serialize settings");
            SPHelper.SaveElement(SPUrlUtility.CombineUrl(webUrl, ConfigFileUrl), newContent);
        }

        public static Settings GetDefault()
        {
            return
                new Settings
                {
                    Log = true
                };
        }
    }
}
